var cartDialog = $("#cartDialog");

$(function() {
	cartDialog.on("click", ".weui-mask", function() {
		closeCart();
	});
	cartDialog.find(".check-all").children().on("click", onAllCheckClick);
});

//打开购物车
function openCart() {
	cartDialog.fadeIn(1);
	cartDialog.children(".weui-half-screen-dialog").addClass("weui-half-screen-dialog_show");
}

//关闭购物车
function closeCart() {
	cartDialog.fadeOut(200);
	cartDialog.find("span.number").text("0.00");
	cartDialog.find("i.fa-check-circle").removeClass("checked");
	cartDialog.children(".weui-half-screen-dialog").removeClass("weui-half-screen-dialog_show");
}

//保存订单
function saveOrder() {
	var checkeds = $(".good-item > .left > .fa-check-circle.checked");
	if (checkeds.length <= 0) {
		mobileGlobal.message("请选择要购买的商品");
		return;
	}
	
	var goods = new Array(), formData = new FormData();
	for (var i = 0; i < checkeds.length; i ++) {
		var goodItem = $(checkeds[i]).parent().parent(), goodid = goodItem.attr("data-id");
		
		goods.push(goodid);
		formData.append("ordergoods[" + i + "].goodid", goodid);
		formData.append("ordergoods[" + i + "].goodprice", goodItem.attr("data-price"));
		formData.append("ordergoods[" + i + "].goodnumber", goodItem.find("input").val());
	}
	
	mobileGlobal.openConfirmDialog("确定购买已选择的商品？", function() {
		mobileGlobal.closeConfirmDialog();
		
		mobileGlobal.loading("正在提交数据，请稍后...");
		
		$.ajax({
			url : __mobilectx + "/cybercafe/order/submitOrder.xhtml", 
			data : formData, 
			contentType : false, 
			processData : false, 
			success : function(data, status) {
				mobileGlobal.hideLoading();
				if (data.status) {
					mobileGlobal.openMessageDialog("提交订单成功！", function() {
						mobileGlobal.closeMessageDialog();
						
						submitOrderCallback(goods);
					});
				} else {
					mobileGlobal.openMessageDialog(data.result, function() {
						mobileGlobal.closeMessageDialog();
					});
				}
			}, 
			error : function(xhr, msg, e) {
				mobileGlobal.hideLoading();
				mobileGlobal.openMessageDialog("网络请求错误！", function() {
					mobileGlobal.closeMessageDialog();
				});
			}
		});
	});
}

//提交订单回调
function submitOrderCallback(goods) {
	var selectedGoods = window.localStorage.getItem("selected_goods");
	selectedGoods = (selectedGoods) ? eval("(" + selectedGoods + ")") : {};
	
	for (var i = 0; i < goods.length; i ++) {
		delete selectedGoods[goods[i]];
		
		$("div.good-item[data-id='" + goods[i] + "']").remove();
	}
	
	window.localStorage.setItem("selected_goods", objToStr(selectedGoods));
	
	cumulativeTotalPrice();
	var checkAll = cartDialog.find(".check-all").children("i.fa-check-circle");
	if (checkAll.hasClass("checked")) checkAll.removeClass("checked");
}

//添加到购物车
function addToCart(goodid) {
	openCart();
	
	var selectedGoods = window.localStorage.getItem("selected_goods");
	selectedGoods = (selectedGoods) ? eval("(" + selectedGoods + ")") : {};
	
	if (selectedGoods[goodid]) selectedGoods[goodid] = selectedGoods[goodid] + 1;
	else selectedGoods[goodid] = 1;
	window.localStorage.setItem("selected_goods", objToStr(selectedGoods));
	
	var goods = new Array();
	for (var key in selectedGoods) {
		goods.push(key);
	}
	
	mobileGlobal.sendRequest(__mobilectx + "/cybercafe/good/checkGoods.xhtml", {goods : goods.join(",")}, null, 
		function(data, status) {
			mobileGlobal.hideLoading();
			if (data.status) renderCart(goodid, data.result);
			else {
				mobileGlobal.openMessageDialog(data.result, function() {
					mobileGlobal.closeMessageDialog();
					closeCart();
				});
			}
		}, 
		function(xhr, msg, e) {
			mobileGlobal.hideLoading();
			mobileGlobal.openMessageDialog("网络请求错误！", function() {
				mobileGlobal.closeMessageDialog();
				closeCart();
			});
		}
	);
}

//渲染购物车
function renderCart(goodid, onsales) {
	var goodData = cartDialog.find(".good-data");
	goodData.empty();
	
	var selectedGoods = window.localStorage.getItem("selected_goods");
	selectedGoods = (selectedGoods) ? eval("(" + selectedGoods + ")") : {};
	
	if (onsales.length > 0) {
		for (var i = 0; i < onsales.length; i ++) {
			var onsale = onsales[i], number = selectedGoods[onsale.goodid] || 1;
			
			var html = "<div class='good-item' data-id='" + onsale.goodid + "' data-price='" + onsale.goodprice + "'>" + 
						"<div class='left'>" + 
							"<i class='fa fa-check-circle'></i>" + 
							"<span>" + onsale.goodname + "</span>" + 
						"</div>" + 
						"<div class='center'>￥" + onsale.goodprice.toFixed(2) + "</div>" + 
						"<div class='right'>" + 
							"<i class='fa fa-minus-circle'></i>" + 
							"<input class='weui-input' type='number' value='" + number + "'/>" + 
							"<i class='fa fa-plus-circle'></i>" + 
						"</div>" + 
					   "</div>";
			var goodItem = $(html);
			goodItem.find("i.fa-check-circle").on("click", onItemCheckClick);
			var right = goodItem.find("div.right");
			right.children("i").on("click", onPlusOrMinusClick);
			right.children("input").on("change", onInputChange);
			
			if (goodid == onsale.goodid) goodData.prepend(goodItem);
			else goodData.append(goodItem);
		}
		
		cartDialog.find("div[data-id='" + goodid + "']").find("i.fa-check-circle").click();
	}
	
	var deleteGoods = new Array();
	for (var key in selectedGoods) {
		var found = false;
		for (var i = 0; i < onsales.length; i ++) {
			if (key == onsales[i].goodid) {
				found = true;
				break;
			}
		}
		if (!found) deleteGoods.push(key);
	}
	if (deleteGoods.length > 0) {
		for (var i = 0; i < deleteGoods.length; i ++) {
			delete selectedGoods[deleteGoods[i]];
		}
		window.localStorage.setItem("selected_goods", objToStr(selectedGoods));
	}
}

//全选点击事件
function onAllCheckClick() {
	var checkAll = $(this).parent().children("i.fa-check-circle");
	var checkItems = cartDialog.find(".good-data").find("i.fa-check-circle");
	
	if (checkAll.hasClass("checked")) {
		checkAll.removeClass("checked");
		checkItems.removeClass("checked");
	} else {
		checkAll.addClass("checked");
		checkItems.addClass("checked");
	}
	
	cumulativeTotalPrice();
}

//项选点击事件
function onItemCheckClick() {
	var checkItem = $(this);
	var checkAll = cartDialog.find(".check-all").children("i.fa-check-circle");
	
	if (checkItem.hasClass("checked")) {
		checkItem.removeClass("checked");
		checkAll.removeClass("checked");
	} else {
		checkItem.addClass("checked");
		
		var allChecked = true;
		var checkItems = cartDialog.find(".good-data").find("i.fa-check-circle");
		for (var i = 0; i < checkItems.length; i ++) {
			if (!$(checkItems[i]).hasClass("checked")) {
				allChecked = false;
				break;
			}
		}
		if (allChecked) checkAll.addClass("checked");
	}
	
	cumulativeTotalPrice();
}

//增加减少点击事件
function onPlusOrMinusClick() {
	var sender = $(this), input = sender.siblings("input"), value = parseInt(input.val());
	if (isNaN(value) || value <= 0) value = 1;
	if (sender.hasClass("fa-minus-circle")) {
		if (value > 1) value --;
	} else if (sender.hasClass("fa-plus-circle")) {
		value ++;
	} else return;
	input.val(value);
	
	var goodid = sender.parent().parent().attr("data-id");
	cacheNumberChange(goodid, value);
	
	cumulativeTotalPrice();
}

//输入变化事件
function onInputChange() {
	var sender = $(this), value = parseInt(sender.val());
	if (isNaN(value) || value <= 0) value = 1;
	sender.val(value);
	
	var goodid = sender.parent().parent().attr("data-id");
	cacheNumberChange(goodid, value);
	
	cumulativeTotalPrice();
}

//缓存数量变化
function cacheNumberChange(goodid, number) {
	var selectedGoods = window.localStorage.getItem("selected_goods");
	selectedGoods = (selectedGoods) ? eval("(" + selectedGoods + ")") : {};
	
	if (selectedGoods[goodid]) selectedGoods[goodid] = number;
	else selectedGoods[goodid] = number;
	window.localStorage.setItem("selected_goods", objToStr(selectedGoods));
}

//累加总价
function cumulativeTotalPrice() {
	var totalPrice = 0;
	var checkItems = cartDialog.find(".good-data").find("i.fa-check-circle");
	for (var i = 0; i < checkItems.length; i ++) {
		var checkItem = $(checkItems[i]);
		if (!checkItem.hasClass("checked")) continue;
		
		var goodItem = checkItem.parent().parent();
		var goodPrice = parseFloat(goodItem.attr("data-price"));
		var goodNumber = parseFloat(goodItem.find("input").val());
		totalPrice += goodPrice * goodNumber;
	}
	cartDialog.find("span.number").text(totalPrice.toFixed(2));
}

//对象转字符串
function objToStr(obj) {
	var str = null;
	for (var key in obj) {
		if (str === null) str = "'" + key + "' : " + obj[key];
		else str += ", '" + key + "' : " + obj[key];
	}
	return ((str === null) ? "{}" : "{" + str + "}");
}
